package com.tsing.cli.common.core.config;

import com.tsing.cli.common.core.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步配置类
 *
 * @author TheTsing
 */
@Slf4j
@EnableAsync
@AutoConfiguration
public class AsyncConfiguration implements AsyncConfigurer {

    private static final int CORE = Runtime.getRuntime().availableProcessors() + 1;

    @Override
    public Executor getAsyncExecutor() {
        if (SpringUtils.isVirtual()) {
            return new VirtualThreadTaskExecutor("virtual-thread-");
        }
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE);
        executor.setMaxPoolSize(CORE << 1);
        executor.setQueueCapacity(CORE << 1);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("async-thread-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error(ex.getMessage(), ex);
    }

}
